<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="translate('权限分配')"
    @close="close"
  >
    <el-tabs v-model="activeName" @tab-change="handleClick">
      <el-tab-pane :label="translate('用户权限')" name="user" />
      <el-tab-pane :label="translate('按钮权限')" name="button" />
    </el-tabs>
    <div class="menu-management-container">
      <el-row :gutter="20">
        <el-col :lg="10" :md="8" :sm="24" :xl="6" :xs="24">
          <vab-card shadow="hover">
            <el-tree
              ref="treeRef"
              :data="data"
              :default-expanded-keys="expandDefault"
              highlight-current
              node-key="id"
              :props="defaultProps"
              :show-checkbox="activeName != 'user'"
              @check-change="changeTreeCheckbox"
              @node-click="handleNodeClick"
            />
          </vab-card>
        </el-col>
        <el-col :lg="20" :md="16" :sm="24" :xl="18" :xs="24">
          <el-checkbox
            v-model="checkAll"
            :disabled="activeName === 'user' ? false : checkBoxDisabled"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            {{ translate('全选') }}
          </el-checkbox>
          <div>
            <el-checkbox-group
              v-model="checkList"
              :disabled="activeName === 'user' ? false : checkBoxDisabled"
              @change="handleChenckBoxChange"
            >
              <el-checkbox
                v-for="item in list"
                :key="item.value"
                border
                class="checkBox"
                :label="item.id"
              >
                {{ item.text }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <el-button @click="close">{{ translate('取消') }}</el-button>
      <el-button type="primary" @click="save">
        {{ translate('确定') }}
      </el-button>
    </template>
  </el-dialog>
</template>
<script>
  import {
    getButtoneList,
    getModuleTree,
    setAuthorizedSubmit,
    getDepartmentTree,
    getMemberList,
    setAuthorizedMember,
    getUser,
    getButton,
  } from '@/api/roleManagement'
  import { User } from '@element-plus/icons-vue'
  import { componentSizeMap } from 'element-plus'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: '',
    components: {},
    props: {},
    emits: ['refresh-route'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        treeRef: null,
        title: '编辑',
        dialogFormVisible: false,
        expandDefault: [],
        checkList: [],
        treeChecked: [],
        checkBoxDisabled: false,
        defaultCheckList: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        activeName: 'user',
        data: [],
        checkAll: false,
        list: [],
        isIndeterminate: false,
        queryTreeForm: {
          // companyId: '8D3B7E0D-10AE-4E70-96A9-7EDB20C877F7',
          companyId: '1D732F2B-4BFA-40DB-81A0-2BBFC849BD6F',
        },
        queryForm: {
          companyId: 'string',
          roleId: 'string',
          departmentId: 'string',
          viewDetailId: 'string',
          objectId: 'EAEF3CB0-4D33-4E14-AEA7-6324954F3648',
          category: '2',
        },
      })
      const fetchData = async () => {
        const {
          data: { data },
        } =
          state.activeName == 'user'
            ? await getMemberList(state.queryForm)
            : await getButtoneList(state.queryForm)
        state.list = JSON.parse(data)
        // state.checkList = []
        let checkedNum = 0
        // const checkList = []
        //多选框判断选中
        if (state.list.length > 0) {
          state.list.forEach((item) => {
            // checkList.push(item.id)
            if (item.checkstate == 1) {
              checkedNum++
              state.checkList.push(item.id)
              state.checkBoxDisabled = false
            }
          })
        }
        // if (checkedNum === 0) {
        //   state.checkBoxDisabled = true
        // }
        //全选状态判断
        state.isIndeterminate = checkedNum > 0 && checkedNum < state.list.length
        state.checkAll =
          checkedNum === state.list.length && state.list.length > 0
        state.listLoading = false
      }
      //获取树形结构下第一个ID
      const getFirstNode = (tree) => {
        if (tree.ChildNodes.length > 0) {
          getFirstNode(tree.ChildNodes[0])
        } else {
          state.expandDefault.push(tree.id)
          // state.queryForm.objectId = tree.id
          state.queryForm.ModuleId = tree.id
          state.queryForm.departmentId = tree.id
          if (tree.checkstate != 1) state.disabled = true
          return
        }
      }
      //树形结构判断选中
      const getCheckedNode = (val) => {
        if (val.length !== 0) {
          val.forEach((item) => {
            //直接循环
            if (item.checkstate == 1) {
              //判断当前树是否被选中 选中的话就push到 全局变量 treeChecked 里面
              state.treeChecked.push(item.id) //把id push到里面
            }
            if (item.ChildNodes != null || item.ChildNodes.length > 0) {
              //这里是判断下级是否还有数据 下级数据是用 ChildNodes 包起来的
              getCheckedNode(item.ChildNodes)
            }
          })
        }
        state['treeRef'].setCheckedKeys(state.treeChecked)
      }
      //获取选中数组
      const getChecked = async () => {
        const {
          data: { data },
        } =
          state.activeName == 'user'
            ? await getUser(state.queryForm)
            : await getButton(state.queryForm)
        if (data) state.defaultCheckList = JSON.parse(data)
      }
      const getTree = async () => {
        state.listLoading = true
        if (state.activeName == 'user') {
          const {
            data: { dmList },
          } = await getDepartmentTree(state.queryForm)
          state.data = dmList
          if (dmList.length > 0) {
            state.queryForm.ModuleId = dmList[0].id
            state.queryForm.departmentId = dmList[0].id
            // state['treeRef'].setCurrentKey(dmList[0].id)
          }
        } else {
          const {
            data: { data },
          } = await getModuleTree(state.queryForm)
          state.data = JSON.parse(data)
          getFirstNode(state.data[0])
          //重置树形结构选中
          if (state.activeName != 'user') {
            state.treeChecked = []
            getCheckedNode(state.data)
          }
        }
        fetchData()
      }
      //树形结构点击切换
      const handleNodeClick = (row) => {
        state.queryForm.ModuleId = row.id
        state.queryForm.departmentId = row.id
        fetchData()
      }
      //全选
      const handleCheckAllChange = (val) => {
        state.checkList = val ? state.list.map((item) => item.id) : []
        state.isIndeterminate = false
        changeCheckBox(state.checkList)
      }
      //改变选中的的按钮数组
      const changeCheckBox = (val) => {
        let flag = true
        if (state.defaultCheckList.length > 0) {
          state.defaultCheckList.forEach((item) => {
            if (item.id == state.queryForm.ModuleId) {
              item.checked = val
              flag = false
            }
          })
        }
        if (flag) {
          state.defaultCheckList.push({
            id: state.queryForm.ModuleId,
            checked: val,
          })
        }
      }
      //多选
      const handleChenckBoxChange = (value) => {
        const checkedCount = value.length
        state.checkAll = checkedCount === state.list.length
        state.isIndeterminate =
          checkedCount > 0 && checkedCount < state.list.length
        changeCheckBox(value)
      }
      const changeTreeCheckbox = (node, checked) => {
        //取消左侧选中，去除右侧多选择选中
        debugger
        if (!checked) {
          state.checkList = []
          state.isIndeterminate = false
        }
        state.checkBoxDisabled = !checked
      }
      const close = () => {
        state.form = {
          meta: {
            icon: '',
          },
        }
        state.dialogFormVisible = false
      }
      const showEdit = (row, id) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
        }
        state.queryForm.companyId = row.companyId
        state.queryForm.objectId = id
        state.queryForm.roleId = id
        getTree()
        getChecked()
        state.dialogFormVisible = true
      }
      const handleClick = (val) => {
        getTree()
        getChecked()
      }
      const save = async () => {
        let arr = []
        if (state.defaultCheckList.length > 0) {
          state.defaultCheckList.forEach((item) => {
            if (item.checked.length > 0) {
              arr = [...new Set(arr.concat(item.checked))]
            }
          })
        }
        //半选状态
        const arr1 = state['treeRef'].getHalfCheckedKeys(true)
        const arr2 = state['treeRef'].getCheckedKeys()
        for (const i in arr1) {
          arr2.push(arr1[i])
        }
        // return
        const params = {
          moduleButtonId: arr ? arr.join(',') : '',
          userId: arr ? arr.join(',') : '',
          objectId: state.queryForm.objectId,
          moduleId: arr2 ? arr2.join(',') : '',
          companyId: state.queryForm.companyId,
          viewDetailId: 'string',
          category: '2',
        }
        const { message } =
          state.activeName == 'user'
            ? await setAuthorizedMember(params)
            : await setAuthorizedSubmit(params)
        $baseMessage(message, 'success', 'vab-hey-message-success')
        close()
        // emit('refresh-route')
      }
      // onMounted(() => {
      //   getTree()
      // })
      return {
        ...toRefs(state),
        handleCheckAllChange,
        handleChenckBoxChange,
        handleNodeClick,
        close,
        fetchData,
        save,
        showEdit,
        getFirstNode,
        handleClick,
        getCheckedNode,
        getChecked,
        changeCheckBox,
        changeTreeCheckbox,
        translate,
      }
    },
  })
</script>
<style scoped>
  .checkBox {
    width: 140px;
    margin-top: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
